import copy
import datetime
import json
import pathlib
import time

from model import Project as ModelProject
from playhouse.shortcuts import model_to_dict, dict_to_model
import utils.jsonData as JsonData
from utils.common import *
from entity import Project
from entity.Prosumer import PRODUCER
import utils.prosumer_task as ProsumerTask

from peewee import SQL


def query_project():
    """查询所有项目信息"""
    _res = ModelProject.Project.select()
    _list = []
    for i in _res:
        _list.append(model_to_dict(i))
    return JsonData.JsonData().success_data(msg="查询项目信息成功", data=_list)


def query_project_by_id(project_id):
    """通过id查询项目信息"""
    name = ""
    status = False
    update_time = ""
    for i in ModelProject.Project.select().where(ModelProject.Project.id == project_id):
        name = i.name
        status = i.status
        update_time = i.update_time
    das_path = pathlib.Path(".").absolute()
    if name == "" or name is None:
        return False, JsonData.JsonData().error(code="1005", msg="查询失败，找不到这个项目编号")
    _res = {
        "name": name,
        "status": status,
        "update_time": update_time,
        "project_path": str(das_path / "project" / f"{name}{project_id}"),
        "project_file_path": str(das_path / "project" / f"{name}.dsft.ini")
    }
    return True, JsonData.JsonData().success_data(msg="查询项目信息成功", data=[_res])


def delete_project_by_id(project_id):
    """通过id删除项目信息, 1005,删除失败，返回失败原因"""
    # 删除本地文件
    delete_project_by_id_from_local(project_id, 1)

    _res = ModelProject.Project.delete().where(ModelProject.Project.id == project_id).execute()
    if not _res:
        return JsonData.JsonData.JsonData().error(code="1005", msg="删除失败，找不到这个项目编号")
    return JsonData.JsonData().success()


def delete_project_by_id_from_local(project_id, signal=0):
    """通过id查询项目信息，删除在本地的项目文件
    """
    judge, _res = query_project_by_id(project_id)
    if not judge:
        return False
    _res = json.loads(_res)
    _data = _res["data"][0]
    project_path = _data["project_path"]
    project_file_path = _data["project_file_path"]
    if signal:
        remove_dir(project_path)
    remove_file(project_file_path)
    return True


def create_project(project_name):
    """创建一个项目信息"""
    _res = ModelProject.Project(name=project_name,
                                update_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                status=False).save()
    if _res:
        delete_project_by_id_from_local(get_next_id())
        return JsonData.JsonData().success([get_next_id()])
    delete_project_by_id_from_local(get_next_id(), 1)
    return JsonData.JsonData().error(code="1006", msg="上传失败，服务器好像出现问题了！请重试")


def get_next_id():
    """查询下一个项目编号"""
    project_max_id = 0
    for i in ModelProject.Project.select(SQL("max(t1.id)")):
        project_max_id = i.id
    return str(project_max_id)


def query_project_config_by_id(project_id):
    """通过id查询项目的配置信息"""
    judge, project = query_project_by_id(project_id)
    if not judge:
        return project
    project = json.loads(project)["data"][0]
    project_config_path = pathlib.Path(project["project_path"] + "\\app.dsft.ini")
    project_path = pathlib.Path(project["project_path"])
    if not project_path.is_dir():
        return JsonData.JsonData().error(code="1005", msg="查询失败，找不到这个项目，建议删除数据表")
    project = Project.Project(project_path, project_config_path)
    project.config.read_config()
    _res = project.__dict__
    _res["project"] = str(_res["project"])
    _res["config"] = project.config.__dict__
    return JsonData.JsonData().success([_res])


def update_project_update_time(project_id):
    """通过id更新update_time字段"""
    return ModelProject.Project.update({
        ModelProject.Project.update_time: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }).where(
        ModelProject.Project.id == project_id).execute()


def get_project_update_time(project_id):
    """根据id查询项目的最后更新时间,返回时间戳"""
    update_time = ModelProject.Project.get(ModelProject.Project.id == project_id).update_time
    return int(update_time.timestamp())


def update_project_config(project_id, project_config):
    """通过id更新本地配置文件，并且更新时间至数据库"""
    project_path = pathlib.Path() / "project" / project_config["name"]
    if not project_path.is_dir():
        return JsonData.JsonData().error(code="1008", msg="查询失败，找不到这个项目，建议删除数据表")
    if not update_project_update_time(int(project_id)):
        return JsonData.JsonData().error(code="1008", msg="更新数据库失败，请重试")
    project = Project.Project(project_path, project_path / "app.dsft.ini")
    project.config.read_config()
    project.config.__dict__ = project_config
    project.config.config_path = project_path / "app.dsft.ini"
    project.config.save()
    return JsonData.JsonData().success("项目配置更新成功")


def update_project_by_id(project_id, file, ip):
    """通过id更新项目文件，信息更新至数据库"""
    judge, _res = query_project_by_id(project_id)
    if not judge:
        return _res
    project = json.loads(_res)["data"][0]
    return check_and_extract_project(file, project["project_path"], 1)

